package posecco.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import posecco.shared.Util;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PoSecCo implements EntryPoint {

	/**
	 * This is the entry point method.
	 */
	
	private User user = null;
	private static PoSecCo instance;
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);
	
	public PoSecCo() {
		
		RootPanel.get("header").clear();
		RootPanel.get("header").add(new HTML("<h1>" + Util.getMessage("title") + "</h1>"));
		String sessionId = Cookies.getCookie("sid");
		if (sessionId != null) {
			
			loginUserBySessionId(sessionId);
		}
	}
	
	public static PoSecCo getInstance() {
		
		if (instance == null) {
			
			instance = new PoSecCo();
		}
		return instance;
	}
	public User getUser() {
		return user;
	}

	public void onModuleLoad() {
		
		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		Element loaderDiv = RootPanel.get("loader").getElement();
		RootPanel.setVisible(loaderDiv, false);
		RootPanel.get("nav").add(new Navigation());
	}
	
	public void setUser(User user) {
		
		this.user = user;
	}
	
	public void loginUserBySessionId(String sId) {
		
		// this.user = user;
		loginService.getUserBySessionId(sId, new AsyncCallback<User>() {
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				Navigation.gotoPage("login");
			}

			public void onSuccess(User result) {
				try {	
					if (result != null) {
						setUser(result);
						Navigation.gotoPage("userList");
						RootPanel.get("userBox").clear();
						RootPanel.get("userBox").add(new HTML(Util.getMessage("greeting") + " " + result.getLogin()));
					}
					else {
						Navigation.gotoPage("login");
					}
				}
				catch (NullPointerException e) {
					Navigation.gotoPage("login");
				}
			}
		});
	}
}
